"use client";
import { debounce } from 'lodash';
import { use, useEffect, useRef, useState } from 'react';
import { fetchApi, fetchWithAuth } from "@/request/request";
import { poupp } from '@/components/ui/popup';
import { showToast } from '@/components/ui/toast';
import { useRouter } from '@/utils/router';
import { Readerbar } from '@/components/NavBar/readerBar';
import PopupQuiz from '@/components/popupQuiz/index';
import { usePlayStore } from '@/store/setPlayAudio';


export default function Reader() {
    const { chat_id, currentPath } = useRouter();
    const itemRefs = useRef<(HTMLDivElement | null)[]>([]); // 正确定义类型
    const [current, setCurrent] = useState<any>(null)//播放的位置
    const [openQuiz, setOpenQuiz] = useState<boolean>(false)//打开刷题
    const [highlight, setHighlight] = useState<Array<number>>([])//查看答案时，高亮
    const article = useRef<({ id: string, content: { id: number, text: string }[] } | null)>(null)
    const [bookInfo, setBookInfo] = useState<any>({ id: '', text: '', collect: false, quiz: false, audio: false, title: "" });
    const { audio, isPlaying, setPlayAudio, pauseAudio, resumeAudio, stopAudio } = usePlayStore();
    const [readTxt, setReadTxt] = useState<{ id: number, en_text: string, zh_text: string, text_list: string[], trans: boolean }[]>([]);

    const toTextList = (text: Array<any>) => {
        return text.map((e) => {
            return {
                ...e,
                text_list: e.en_text.split(" "),
                trans: false,  // 添加缺失的 `trans` 字段
            }
        })
    }
    //加入书架
    const allShelf = async () => {
        const res = await fetchWithAuth("/api/auth/collect", {
            action: "add", params: {
                bookId: chat_id
            }
        }) as any
        if (res.message == "success") {
            if (!bookInfo.collect) {
                showToast("加入书籍")
                setBookInfo({
                    ...bookInfo,
                    collect: true
                })
            } else {
                showToast("移除书书籍")
                setBookInfo({
                    ...bookInfo,
                    collect: false
                })
            }
        } else {
            showToast("添加失败")
        }
    }

    const handleBar = (type: string) => {
        switch (type) {
            case "quiz":
                setOpenQuiz(!openQuiz)
                break;
            case "collect":
                allShelf()
                break;
            default:
                break;
        }
    }

    //初始化
    useEffect(() => {
        if (chat_id) {
            //初始化
            fetchApi("/api/translate", { action: "init", params: { chat_id } })
                .then((res: any) => {
                    const title = res.data.title
                    const newText = toTextList(res.data.content)
                    const content = newText.map((e) => ({
                        text: e.en_text,
                        id: e.id,
                    })) as [{ id: number, text: string }]
                    article.current = { id: chat_id, content }
                    setBookInfo({ ...bookInfo, id: chat_id, text: content, title: title })
                    setReadTxt(newText)
                }).catch((err) => {
                    console.log(err);
                    showToast("加载失败")
                });

        }
        //判断是否收藏
        const userInfo = localStorage.getItem("user") || "{}";
        const user = JSON.parse(userInfo);
        if (user.id) {
            fetchApi("/api/translate", {
                action: "check", params: { chat_id, id: user.id }
            }).then((res: any) => {
                if (res.data.exists) {
                    setBookInfo({
                        ...bookInfo,
                        collect: true
                    })
                } else {
                    setBookInfo({
                        ...bookInfo,
                        collect: false
                    })
                }
            })
        }
    }, [chat_id]);

    const title = bookInfo.title || ""
    useEffect(() => {
        const interval = setInterval(() => {
            const list = currentPath.split("/")[1]
            const user = localStorage.getItem("user") || null
            if (list == "reader" && user) {
                // console.log(title)
                fetchWithAuth(`/api/auth/user`, { action: "time", params: { title: title } })
            }
        }, 2 * 60 * 1000); // 5 分钟 = 30 0,000 毫秒

        return () => clearInterval(interval); // 组件卸载时清除定时器
    }, [currentPath, title]); // 监听 currentPath 变化
    //翻译句子
    const handleTranslate = async (id: number) => {
        const item = readTxt.find(item => item.id === id) as any;
        // console.log(item.zh_text)
        if (item.zh_text == "没有翻译" || !item.zh_text) {
            const word = await fetchApi(`/api/translate`,
                { action: "translate", params: { "text": item.en_text } }) as any;
            const zh_text = word.data.text;
            setReadTxt(prevState =>
                prevState.map(item =>
                    item.id === id ? { ...item, zh_text: zh_text } : item
                )
            );
            // 获取最新的状态
            const updatedReadTxt = readTxt.map(item =>
                item.id === id ? { ...item, zh_text } : item
            );

            // 发送 API 请求，确保 readTxt 是最新的
            await fetchApi("/api/translate", {
                action: "update",
                params: { chat_id, readTxt: updatedReadTxt }
            });
        }

        setReadTxt(prevState =>
            prevState.map(item =>
                item.id === id ? { ...item, trans: !item.trans } : item
            )
        );
    }

    const playAudio = async (all: boolean, id: number) => {
        if (all) {
            //查看是否在播放
            const isPlaying = usePlayStore.getState().isPlaying;
            // if (isPlaying) {
            // 停止音频播放
            stopAudio();
            // }
            setBookInfo({ ...bookInfo, audio: !bookInfo.audio })
            // const content = readTxt.map((e) => e.en_text)
            console.log(bookInfo.text.split("\n"))
            setPlayAudio(bookInfo.text.split("\n"));
            setCurrent('')
            stopAudio();
        } else {
            const audio = usePlayStore.getState().audio || []
            // console.log(audio)
            if (audio?.length > 1) {
                showToast("正在全文音频播放，先暂停")
            } else {
                // stopAudio();
                const text = readTxt.find(item => item.id === id) as any;
                setPlayAudio([text.en_text]);
                stopAudio();
            }

        }
        // if (audio?.length == 1) {
        //     setPlayAudio([text.en_text]);
        // }
        // 播放音频

        // console.log(usePlayStore.getState().audio);

        // 暂停音频
        // pauseAudio();

        // 恢复音频播放
        // resumeAudio();

        // 停止音频播放
        // stopAudio();

        // const text = readTxt.find(item => item.id == id) as any;
        // const res = await fetchApi(`/api/translate`,
        //     { action: "read", params: { text: text.en_text } }, "POST", {}) as any;
        // // const responseText = await res.text();
        // // console.log(responseText, 899889); // 如果不是音频数据，可以看到错误信息
        // const blob = await res.blob();
        // console.log(blob)
        // const audioUrl = URL.createObjectURL(blob);
        // console.log(audioUrl);
        // const audio = new Audio(audioUrl);
        // audio.play().catch(error => console.error("Audio play error:", error));
    }
    //某个单词
    const handleClick = async (e: React.MouseEvent, text: string) => {
        e.stopPropagation(); // 防止点击冒泡
        const userStr = localStorage.getItem('user') || "{}";
        const user = JSON.parse(userStr); // 👈 正确解析 JSON 字符串成对象
        const word = await fetchApi(`/api/translate`,
            { action: "word", params: { id: user.id, text } }) as any;
        const wordList = word.data;

        if (wordList != 0) {
            poupp(e, `
            <div style="max-width:200px;padding: 10px; border-radius: 8px; background: white; border: 1px solid #ccc; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);">
                ${wordList.map((item: { v: any; k: any; }) => `
                <div style="margin-bottom: 5px;">
                    <div style="font-weight: bold;">${item.k}</div>
                    <div style="color: gray;">${item.v}</div>
                </div>`).join('')}
            </div>`
            );
        } else { showToast("没有查询结果") }

        setPlayAudio([text]);
        // playAudio(text);

        // 创建弹窗元素
        // const popup = document.createElement('div');
        // popup.innerText = `您点击了第 ${"index " + 1} 个元素`;
        // popup.style.position = 'absolute';
        // popup.style.left = `${spanRect.left}px`;
        // popup.style.top = `${spanRect.bottom + window.scrollY}px`;
        // popup.style.backgroundColor = 'white';
        // popup.style.border = '1px solid #ccc';
        // popup.style.padding = '10px';
        // popup.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.1)';
        // popup.style.zIndex = '1000';

        // // 将弹窗添加到 body 中
        // document.body.appendChild(popup);

        // // 更新弹窗内容状态
        // setPopupContent(`您点击了第 ${1} 个元素`);

        // // 添加点击事件监听器，点击弹窗外部区域时关闭弹窗
        // const closePopup = (e: MouseEvent) => {
        //     if (!popup.contains(e.target as Node) && e.target !== spanElement) {
        //         popup.remove();
        //         document.removeEventListener('click', closePopup);
        //         setPopupContent(null); // 清空弹窗内容状态
        //     }
        // };
        // document.addEventListener('click', closePopup);
    };

    const handleHover = debounce(async (text: string) => {
        console.log(`Hovered over: ${text}`);

    }, 1500); // 1s 防抖延迟

    usePlayStore.subscribe((state) => {
        console.log("状态更新:", state.currentIndex);
        // setCurrent(state.currentIndex)
        // itemRefs.current[state.currentIndex]?.scrollIntoView({ behavior: "smooth", block: "center" }); // 平滑滚动
    });

    return (
        <>
            <div>
                <Readerbar onClick={handleBar} onPlay={playAudio} allShelf={allShelf} statusInfo={{ openQuiz }}
                    bookInfo={bookInfo} />
            </div>
            <div className='font-[family-name:var(--font-geist-sans)] items-center justify-items-center pt-25'>
                <div className='max-w-7xl'>
                    {readTxt.map((e, index) => {
                        return (
                            <div
                                key={e.id}
                                id={`content-${e.id}`}
                                className={`bg-[#ffffff] p-3 m-2 rounded-lg ${highlight.includes(e.id) && ("border border-[#0285ff]")}`}
                                ref={(el) => { itemRefs.current[index] = el }} // 这里不会返回值
                                onClick={(event) => {
                                    event.stopPropagation(); // 阻止事件冒泡
                                    // 设置定时器，150ms 后执行单击逻辑
                                    // const timer = setTimeout(() =>
                                    handleTranslate(e.id)
                                    // , 550);
                                    // setPressTimer(timer);
                                }}
                                onDoubleClick={(event) => {
                                    event.stopPropagation(); // 阻止事件冒泡
                                    // if (pressTimer) {
                                    //     clearTimeout(pressTimer); // 取消单击事件
                                    //     setPressTimer(null);
                                    // }
                                    playAudio(false, e.id); // 双击触发播放
                                }}
                            >
                                {e.id === 0 ? (<>
                                    <h2 key={e.id} className="text-xl font-bold  text-center w-full">
                                        {e.text_list.map((i: string, j: number) => (
                                            <span
                                                key={`${e.id}-${j}`}
                                                onClick={(event) => {
                                                    event.stopPropagation(); // 阻止事件冒泡
                                                    handleClick(event, i);
                                                }}
                                                // onMouseEnter={() => handleHover(i)}
                                                className="cursor-pointer text-[#1f1f1f] hover:text-blue-500 pd-1"
                                            >
                                                {`${i} `}
                                            </span>
                                        ))}</h2>
                                    {e.trans && (<h2 className="text-xl font-bold text-[#1f1f1f] text-center w-full">{e.zh_text}</h2>)}</>
                                ) : (<>
                                    {e.text_list.map((i: string, j: number) => (
                                        <span
                                            key={`${e.id}-${j}`}
                                            onClick={(event) => {
                                                event.stopPropagation(); // 阻止事件冒泡
                                                handleClick(event, i);
                                            }}
                                            // onMouseEnter={() => handleHover(i)}
                                            className="cursor-pointer text-[#25282f] hover:text-blue-500 pd-1"
                                        >
                                            {`${i} `}
                                        </span>
                                    ))}
                                    {e.trans && (<div className='pt-1 border-t border-t-[#d4d4d4]'>{e.zh_text}</div>)}
                                </>)}
                            </div>
                        );
                    })}
                </div>
            </div>
            <div className={`fixed bottom-0 left-1/2 transform -translate-x-1/2 w-full max-w-7xl h-[50%] p-2 rounded shadow-lg bg-[#bbbbbb] transition-transform duration-300 rounded-lg overflow-auto custom-scrollbar-hide ${openQuiz ? "translate-y-0" : "translate-y-[10000px]"}`}
                style={{
                    scrollbarWidth: 'none',  // Firefox
                    msOverflowStyle: 'none',  // IE 10+
                    // WebkitScrollbar: 'none',  // Chrome, Safari, Edge
                }}
            >
                {article.current && (<PopupQuiz onClose={() => handleBar("quiz")} setHighlight={setHighlight} openQuiz={openQuiz} article={article.current} />)}
            </div>
        </>
    );
}

